unit Bubble;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, ExtCtrls, StdCtrls;

type
  TForm1 = class(TForm)
    Image1: TImage;
    Button1: TButton;
    Timer1: TTimer;
    procedure FormCreate(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure Timer1Timer(Sender: TObject);
  private
    { Private declarations }
  public
    procedure Draw;
    procedure Save;
  end;
const
n = 5;
w = 40;
h = 40;
var
  Form1: TForm1;
  p, t: array of integer;
  step, step2 : integer;
  x, y : integer;
  xt, yt : integer;
implementation

{$R *.dfm}

procedure TForm1.Draw;
var r, i, j : integer;
begin
  r := 15;
  for i:=0 to n-1-step do
  begin
    x := w*(1+step);
    y := h*(1+i);
    for j:=0 to n-1-step do
    begin
      if step<>0 then
      begin
        if t[j] = p[i] then
          yt := h*(1+j);
      end;
      if step=0 then yt:=y;
    end;
    if (step <> 0) then xt := w*step;
    if (step = 0) then xt := w;
    Image1.Canvas.MoveTo(xt, yt);
    Image1.Canvas.LineTo(x, y);
    {Form1.Image1.Canvas.Ellipse(xt-r, yt-r, xt+r, yt+r);}
    Form1.Image1.Canvas.Ellipse(x-r, y-r, x+r, y+r);
    Form1.Image1.Canvas.TextOut(x-Image1.Canvas.TextWidth(inttostr(p[i])) div 2, y-Image1.Canvas.TextHeight(inttostr(p[i])) div 2, Inttostr(p[i]) );
   { Form1.Image1.Canvas.TextOut(xt-Image1.Canvas.TextWidth(inttostr(t[i])) div 2, yt-Image1.Canvas.TextHeight(inttostr(t[i])) div 2, Inttostr(t[i]) ); }
  end;
end;

procedure TForm1.FormCreate(Sender: TObject);
var i:integer;
begin
  Form1.Image1.Canvas.Rectangle(ClientRect);
  setlength(p, n);
  setlength(t, n);
  randomize;
  for i:=0 to n-1 do
  begin;
    p[i] := random(50);
    t[i] := p[i];
  end;
  step := 0;
  step2 := 0;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  FormCreate(Form1);
  Timer1.Enabled := True;
end;

procedure TForm1.Timer1Timer(Sender: TObject);
var temp : integer;
begin
  if p[step2]>p[step2+1] then
  begin
    temp := p[step2];
    p[step2] := p[step2+1];
    p[step2+1] := temp;
  end;
  step2 := step2+1;
  if step2 = n-1 then
  begin
    step2 := 0;
    Draw;
    Save;
    step := step+1;
  end;
end;

procedure TForm1.Save;
var i:integer;
begin
  for i:=0 to n-1 do
    t[i] := p[i];
end;

end.
 